//使用惰性单例模式实现只请求一次权限
//管理单例

Storage.prototype.setExpire = (key, value, expire) => {
    let obj = {
        data: value,
        time: Date.now(),
        expire: expire
    };
    //localStorage 设置的值不能为对象,转为json字符串
    localStorage.setItem(key, JSON.stringify(obj));
}

Storage.prototype.getExpire = key => {
    let val = localStorage.getItem(key);
    if (!val) {
        return val;
    }
    val = JSON.parse(val);
    if (Date.now() - val.time > val.expire) {
        localStorage.removeItem(key);
        return null;
    }else{
        var obj = {
            data: val.data,
            time: Date.now(),
            expire: val.expire
        }
        localStorage.setItem(key,JSON.stringify(obj));
    }
    return val.data;
}

window.onload=function () {
    var ele = document.getElementById("loginOut");
    if(ele){
        ele.addEventListener("click",function(){
            loginOutFunc();
        })
    }

}

var getSingle = function (fn) {
    var result;
    return function () {
        return result || (result = fn.apply(this,arguments))
    }
}
//判断登录信息是否过期
var getAuthority = function () {
    var userInfo;

    var access_token = localStorage.getExpire("access_token");
    if(access_token){
        userInfo=localStorage.getExpire("userInfo");;
    }else{
        layui.use(['layer'], function () {
            var $ = layui.jquery;
            var layer = layui.layer;
            layer.msg("你还没有登录", {icon: 2, time: 1500});
        })
        setTimeout(function () {
            top.location.href=loginPageUrl;
        },2500)
    }
    return userInfo;

}

//获取权限
var getAuthority = getSingle(getAuthority);

// window.onload=function(){
//     //示例获取权限方法
//     var data1 = getAuthority()
// };

/**
 *加密处理
 */
function encryption(params) {
    let {
        data,
        type,
        param,
        key
    } = params
    const result = JSON.parse(JSON.stringify(data))
    if (type === 'Base64') {
        param.forEach(ele => {
            result[ele] = btoa(result[ele])
        })
    } else {
        param.forEach(ele => {
            var data = result[ele]
            key = CryptoJS.enc.Latin1.parse(key)
            var iv = key
            // 加密
            var encrypted = CryptoJS.AES.encrypt(
                data,
                key, {
                    iv: iv,
                    mode: CryptoJS.mode.CBC,
                    // padding: CryptoJS.pad.ZeroPadding
                    padding: CryptoJS.pad.Pkcs7
                })
            result[ele] = encrypted.toString()
        })
    }
    return result
}

// 获取用户信息
// function getUserInfo(callback) {
//     var access_token = localStorage.getExpire("access_token");
//     if(access_token){
//         callback();
//     }else{
//         layui.use(['layer'], function () {
//             var $ = layui.jquery;
//             var layer = layui.layer;
//             layer.msg("你还没有登录", {icon: 2, time: 1500});
//         })
//         setTimeout(function () {
//             top.location.href=loginPageUrl;
//         },2500)
//     }
// }
// 获取用户信息
function getUserInfo() {
    var access_token = localStorage.getExpire("access_token");
    axios.get(loginUrl.userInfo,{
        params: {
            access_token: access_token
        }
    })
        .then(function (response) {
            if(response.status == 200 &&response.data.message == "success"){
                let userInfo = response.data.data;
                if(userInfo.sysUser.delFlag==2){
                    localStorage.setExpire("userInfo",JSON.stringify(response.data.data),sysTimeOut)
                    location.href=fogetPageUrl;
                }else{
                    localStorage.setExpire("userInfo",JSON.stringify(response.data.data),sysTimeOut)
                    location.href=webBaseUrl+'/index.html';
                }
            }
        })
        .catch(function (error) {
            console.log(error);
        });
}


function loginOutFunc(){
    localStorage.clear();
    top.location.href=loginPageUrl;
}

//根据名称获取url参数
function getQueryString(name){
    let reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
    let r = window.location.search.substr(1).match(reg);
    if (r != null) {
        return unescape(r[2]);
    };
    return null;
}


//系统对接-调用对方接口用token获取用户信息
function getInfoByToken(token,callback){
    axios({
        method: 'get',
        url:loginConnect.getInfoByToken,
        headers:{
            'TENANT-ID': '1',
            'Authorization': 'Bearer '+token,
        }
    })
        .then(function (response) {
            if(response.status == 200){
                var data = response.data;
                callback&&callback(data)
            }else {
                callback&&callback(response.data)
            }
        })
        .catch(function (error) {
            callback&&callback(error)
            console.log(error);
        });
}

//调用对方接口获取统计局代码
function gettjjcode(userparams){
    // let userparams = {
    //     username:'zj',
    //     password:'111111',
    //     grant_type:'password',
    //     scope:'server'
    // }
    let testreq = {
        data: userparams,
        key: 'yswlyswlyswlyswl',
        param: ['password']
    }

    let password = encryption(testreq);

    axios({
        method: 'post',
        url:loginConnect.gettjjcode,
        data:$.param(password),
        headers:{
            'isToken': false,
            'TENANT-ID': '1',
            'Authorization': 'Basic eXN3bDp5c3ds'}
    })
        .then(function (response) {
            if(response.status == 200){
                var data = response.data;
                getInfoByToken(data.access_token);
                return data;
            }else {
                console.log(response.data)
            }
        })
        .catch(function (error) {
            console.log(error);

        });
}


function getUserName(tjjCode,callback) {
    let req = {
        auth:'9AF862B3845A779C0BB55EA369FD3440',
        tjjCode:tjjCode
    }
    axios({
        method: 'get',
        url:loginConnect.getUserName,
        params:req
    })
        .then(function (response) {
            if(response.status == 200){
                var data = response.data;
                callback&&callback(data)
            }else {
                callback&&callback(response.data)
            }
        })
        .catch(function (error) {
            callback&&callback(error)
            console.log(error);
        });
}

function login(req,callback){
    axios({
        method: 'post',
        url:loginUrl.tokenUrl,
        data:$.param(req),
        headers:{
            'Content-Type':'application/x-www-form-urlencoded'}
    })
        .then(function (response) {
            if(response.status == 200){
                callback&&callback(response);
            }else {
                callback&&callback(response);
            }
        })
        .catch(function (error) {
            callback&&callback(error);
            console.log(error);
            // var response = error.response;
            // var data = response.data;
            // layer.msg(data.message, {icon: 2, time: 1500});
        });
}

var key = CryptoJS.enc.Utf8.parse("cBssbHB3ZA==HKXT");
function aesEncode(str) {
    var encryptedData = CryptoJS.AES.encrypt(str, key, {
        mode: CryptoJS.mode.ECB,
        padding: CryptoJS.pad.Pkcs7
    });
    return encryptedData.toString();
}


//记住密码
function rememberPassword(user){
    if(user.isRememberPwd == "on"){
        var username = user.username;
        var password = user.password;
        if (username != "" && password != "") {
            SetCookie(username, password);
        }else{
            SetCookie("", "");
        }
    }else{
        document.cookie = "username= "
    }
}
function SetCookie(username, password) {
    var Then = new Date();
    Then.setTime(Then.getTime() + 1866240000000);
    document.cookie = "username=" + username + "%%" + password + ";expires=" + Then.toGMTString();
}
